import { getClassList } from "@/request/user"
import {
  Message
} from 'ant-design-vue';

const state = {
  classList: [],
  markGetClass: false
}

const mutations = {
  // 保存班级列表
  setClassList(state, payload) {
    state.classList = payload
  },
  // 标记是否发送过获取班级列表请求
  setMarkGetClass(state, payload) {
    state.markGetClass = payload
  }
}

const actions = {
  // 将班级ID列表转换为班级
  async classIdToClassName({
    commit,
    state,
    dispatch
  }, val) {
    const cData = val;
    if (cData.classIDList) {
      const classList = await dispatch("gClassList");
      return classList
        .filter((item) =>
          cData.classIDList.split(",").includes(`${item.classID}`)
        );
      // .map((item) => item.className)
      // .join(",")
    }
  },
  async gClassList({ commit, state, dispatch }) {
    if (state.classList.length) {
      return state.classList
    } else {
      const list = await dispatch('getClass')
      return list
    }
  },
  async getClass({ commit, state, dispatch }) {
    // if (state.markGetClass) return []
    commit('setMarkGetClass', true)
    const data = await getClassList({classType: 'all'});
    if (data) {
      commit('setClassList', data)
      return data
    }
    else return Message.error({ content: '获取班级列表失败' }) && commit('setMarkGetClass', true)
  },
  // 通过班级名称获取班级ID
  async getClassID({ commit, state, dispatch }, className) {
    const classList = await dispatch("gClassList");
    if (!classList) return undefined
    const findClass = classList.find((item) => item.className == className);
    return findClass?.classID;
  },
  // 获取班级名称
  async getClassName({dispatch}, classID) {
    const classList = await dispatch("gClassList");
    if (!classList) return undefined
    const findClass = classList.find((item) => item.classID == classID);
    return findClass?.className;
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}